<?php
/**
 * 管理员后台控制器
 * 
 * @version $Id: Class.php 647 2013-01-23 06:39:11Z linsir123 $
 */
class controllerClass extends AdminController 
{
	/**
	 * @var 模型
	 */
	public $mClasses;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->mClasses = MA::classes();
	}
	
	/**
	 * 首页
	 */
	public function actionIndex()
	{
		if (Request::isPost() || isset($_GET['refresh'])) {
			$this->_initSession();
			
			///
			$data = $_SESSION['MY_LIST'];
			$list = $data['list'];
			$index = $data['index'];
			$list2 = $data['list2'];
			$index2 = $data['index2'];
			if (isset($list[$index])) {
				list($parentId, $title) = $list[$index];
				if (count($list2) == $index2) {
					$this->_echo("");
					$this->_echo($index ." >--------------------------------------------------------------------");
					
					///
					$index2 = 0;
					$list2 = $this->mClasses->getTopSub($parentId);
					$this->_save(0, $parentId, $title);
				}
				
				///
				$i = 0;
				$step = 0;
				foreach ($list2 as $classId => $v) {
					if (++$i > $index2 && $step < 10) {
						$index2++;
						$step++;
						$this->_save($parentId, $classId, $v);
					}
				}
				
				///
				echo '<html><head><meta http-equiv="refresh" content="1;URL=?refresh" /></head></html>';
				if (count($list2) == $index2) 
					$index++;
			}
			$_SESSION['MY_LIST']['index'] = $index;
			$_SESSION['MY_LIST']['index2'] = $index2;
			$_SESSION['MY_LIST']['list2'] = $list2;
		} else {
			View::display('class/index');
			View::assignSet(array(
				'title' => '分类',
			));
		}
	}
	
	
	/// 以下为私有方法 ///
	
	
	/**
	 * 初始化
	 */
	private function _initSession()
	{
		@session_start();
		
		///
		if ( ! isset($_SESSION['MY_LIST'])) {
			$list = array();
			$subs = $this->mClasses->getTopSub(0);
			foreach ($subs as $parentId => $title) 
				$list[] = array($parentId, $title);
				
			$data = $_SESSION['MY_LIST'] = array(
				'index' => 0,
				'list' => $list,
				'index2' => 0,
				'list2' => array(),
			);
		}
	}
	
	/**
	 * 保存
	 */
	private function _save($parentId, $classId, $title)
	{
		$id = $this->mClasses->save($parentId, $classId, $title);
		///
		$this->_echo($id ." || ". $parentId ." || ". $classId ." || ". $title);
	}
	
	/**
	 * 输出
	 */
	private function _echo($message)
	{
		echo '<script type="text/javascript">parent.displayResult("', $message, '");</script><br />';
		
		///
		ob_flush();
		flush();
	}
}
